package bdz.projects.cbt.ui
{
	import bdz.common.events.DispatchChannel;
	import bdz.projects.cbt.events.CBTGameEvent;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.getDefinitionByName;
	import flash.utils.setTimeout;

	public class CBTList extends MovieClip {
		
		protected var _renderer:String;
		protected var _items:Array;
		protected var _created:Boolean = false;
		protected var _uiref:Array;
		protected var _starty:Number = 29 ;
		protected var _startx:Number = 1;
		protected var _lastSelected:MovieClip;
		protected var _channel:DispatchChannel = DispatchChannel.getChannel();
		
		public function CBTList() {
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, initializeComponent);
		}
		protected function onGameChanged(evt:CBTGameEvent):void{
			
		}
		protected function initializeComponent(evt:Event):void{
			_created = true;
			if(_renderer){
				renderItems();			
			}
		}
		
		protected function renderItems():void{
			clear();
			_uiref = new Array();
			var sy:Number = _starty;
			
			for each(var o:* in _items){
				var torender:Object = getDefinitionByName(_renderer);
				var ref:MovieClip = new torender() as MovieClip;
				
				ref.addEventListener(MouseEvent.CLICK, onSelectItem);
				ref.doubleClickEnabled = true;
				ref.info = o;
				ref.x = _startx;
				ref.y = sy;
				sy += ref.height;
				_uiref.push(addChild(ref));
				ref.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClickItem);
			}
			
			setTimeout(itemsRendered, 200);
			
		}
		protected function itemsRendered():void{
			
		}
		protected function onDoubleClickItem(evt:MouseEvent):void{
			
			if(_lastSelected && _lastSelected != evt.target) {
				_lastSelected.deselect();
			}
			evt.target.select();
			_lastSelected = evt.target as MovieClip;
		}
		protected function onSelectItem(evt:MouseEvent):void{
			if(_lastSelected){
				_lastSelected.deselect();
			}
			evt.target.select();
			_lastSelected = evt.target as MovieClip;
		}
		public function clear():void{
			if(_uiref && _uiref.length){
				for each(var mc:MovieClip in _uiref){
					try{
						removeChild(mc);
					}catch(e:Error){}
				}
			}
		}
		public function fullClear():void{
			clear();
			_items = [];
		}
		public function removeSelection():void{
			if(_lastSelected){
				_lastSelected.deselect();
				_lastSelected = null;
			}
		}
		public function set dataProvider(arr:Array):void{
			_items = arr;
			if(_created){
				renderItems();
			}
		}
		
		public function get dataProvider():Array{
			return _items;
		}
		public function set renderer(str:String):void{
			_renderer = str;	
		}
		public function get renderer():String{
			return _renderer;
		}
		
	}
}